<template>
  <div class="mod-purchase">
    <data-table ref="dataTableRef" :criterias="table.criterias" :initLoad="true" name="purchase" url="/ware/purchase/select">
      <!-- ----------------------------------------- 查询条件 ----------------------------------------- -->
      <template v-slot:search="criterias">
        <dt-search-item label="仓库">
          <wareinfo-select v-model="criterias.wareId"></wareinfo-select>
        </dt-search-item>
        <dt-search-item label="采购状态">
          <el-select v-model="criterias.status" placeholder="请选择采购状态" clearable>
            <el-option label="新建" :value="0"></el-option>
            <el-option label="已分配" :value="1"></el-option>
            <el-option label="已领取" :value="2"></el-option>
            <el-option label="已完成" :value="3"></el-option>
            <el-option label="有异常" :value="4"></el-option>
          </el-select>
        </dt-search-item>
        <dt-search-item label="检索信息">
          <el-input v-model="criterias.content" maxlength="50" placeholder="请输入分配人员名称/联系电话"></el-input>
        </dt-search-item>
      </template>
      <!-- ------------------------------------------ 工具栏 ------------------------------------------ -->
      <template v-slot:toolbar>
        <el-button-group>
          <el-button v-if="admin.isAuth('ware:purchase:save')" @click="() => addDataEvent()" type="primary">
            新增
          </el-button>
          <el-button v-if="admin.isAuth('ware:purchase:save')" @click="() => updateDataEvent()" type="warning">
            修改
          </el-button>
          <el-button v-if="admin.isAuth('ware:purchase:delete')" @click="() => deleteDataEvent()" type="danger">
            删除
          </el-button>
          <el-button v-if="admin.isAuth('ware:purchase:assignee')" @click="() => assigneePurchaseEvent()" type="success">
            分配任务
          </el-button>
          <el-button v-if="admin.isAuth('ware:purchase:received')" @click="() => receivedPurchaseEvent()" type="primary">
            领取任务
          </el-button>
          <el-button v-if="admin.isAuth('ware:purchase:finished')" @click="() => finishedPurchaseEvent()" type="info">
            采购完成
          </el-button>
        </el-button-group>
      </template>
      <!-- ---------------------------------------- 数据表格列 ---------------------------------------- -->
      <el-table-column fixed prop="id" align="center" label="采购单ID" width="180" />
      <el-table-column prop="assigneeName" align="left" label="分配人员名称" width="120" />
      <el-table-column prop="phone" align="center" label="联系电话" width="160" />
      <el-table-column prop="priority" align="center" label="优先级" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.priority <= 3" type="info">{{scope.row.priority}}</el-tag>
          <el-tag v-if="scope.row.priority > 3 && scope.row.priority <= 6" type="warning">{{scope.row.priority}}</el-tag>
          <el-tag v-if="scope.row.priority > 6" type="danger">{{scope.row.priority}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="采购状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0">新建</el-tag>
          <el-tag v-if="scope.row.status === 1">已分配</el-tag>
          <el-tag v-if="scope.row.status === 2">已领取</el-tag>
          <el-tag v-if="scope.row.status === 3">已完成</el-tag>
          <el-tag v-if="scope.row.status === 4">有异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="wareName" align="left" label="仓库名称" width="260" show-overflow-tooltip />
      <el-table-column prop="amount" align="right" label="总金额" width="120" />
      <el-table-column prop="createTime" align="center" label="创建时间" width="180" />
      <el-table-column prop="updateTime" align="center" label="更新时间" width="180" />
    </data-table>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateRef" @loadTableData="loadTableData"></add-or-update>
    <purchase-assignee v-if="assigneeVisible" ref="purchaseAssigneeRef" @loadTableData="loadTableData"></purchase-assignee>
  </div>
</template>
<script lang="ts" setup>
import admin from "@/utils/admin";
import http from "@/utils/httpRequest";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, nextTick, reactive } from "vue";

import WareinfoSelect from "../common/wareinfo-select.vue";
import AddOrUpdate from "./purchase-add-or-update.vue";
import PurchaseAssignee from "./purchase-assignee.vue";

// 数据表格
const table = reactive({
  criterias: {
    wareId: "",
    status: "",
    content: "",
  },
});

// 数据表格引用
const dataTableRef = ref();

// 弹窗引用
const addOrUpdateRef = ref();

// 分配弹窗引用
const purchaseAssigneeRef = ref();

// 分配窗口是否显示
const assigneeVisible = ref(false);

// 新增修改弹窗是否显示
const addOrUpdateVisible = ref(false);

// 新增
const addDataEvent = async () => {
  addOrUpdateVisible.value = true;
  await nextTick();
  addOrUpdateRef.value.initForm("add");
};

// 修改
const updateDataEvent = async () => {
  // 验证并获取是否选择一条数据
  let data = admin.obtainOneSelectionTableData(dataTableRef.value);
  if (!data) {
    return;
  }
  addOrUpdateVisible.value = true;
  await nextTick();
  addOrUpdateRef.value.initForm("update", data);
};

// 删除
const deleteDataEvent = () => {
  admin.batchDeleteSelectionTableData(dataTableRef.value, "/ware/purchase/delete");
};

// 分配采购任务
const assigneePurchaseEvent = async () => {
  let data = admin.obtainOneSelectionTableData(dataTableRef.value);
  if (!data) {
    return;
  }
  assigneeVisible.value = true;
  await nextTick();
  purchaseAssigneeRef.value.initForm(data);
};

// 领取采购任务
const receivedPurchaseEvent = () => {
  ElMessageBox
    .confirm(`领取操作应在移动APP等其他系统操作，此为模拟操作，请点击【确认】按钮进行领取操作！`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      let selection = dataTableRef.value.getSelection();
      if (!selection || selection.length <= 0) {
        ElMessage.error("请选择要领取的采购任务！");
        return;
      }
      let receivedIds = [];
      for (let i = 0; i < selection.length; i++) {
        receivedIds.push(selection[i]["id"]);
      }
      http
        .instance({
          url: http.adornUrl("/ware/purchase/received"),
          method: "post",
          data: http.adornData(receivedIds, false),
        }).then(({ data }) => {
          if (http.success(data, true, true)) {
            loadTableData();
          }
        });
    })
    .catch(()=>{});
};

// 完成采购任务
const finishedPurchaseEvent = () => {
  ElMessageBox
    .confirm(`结束采购任务操作应在移动APP等其他系统操作，此为模拟操作，请点击【确认】按钮进行结束操作！`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      let selection = dataTableRef.value.getSelection();
      if (!selection || selection.length <= 0) {
        ElMessage.error("请选择要结束的采购任务！");
        return;
      }
      let finishedIds = [];
      for (let i = 0; i < selection.length; i++) {
        finishedIds.push(selection[i]["id"]);
      }
      http
        .instance({
          url: http.adornUrl("/ware/purchase/finished"),
          method: "post",
          data: http.adornData(finishedIds, false),
        }).then(({ data }) => {
          if (http.success(data, true, true)) {
            loadTableData();
          }
        });
    })
    .catch(()=>{});
};

// 表格数据加载
const loadTableData = () => {
  dataTableRef.value.loadTableData();
};
</script>
